package br.uneb.tebd.webservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;

public class WebServiceClient {

	public static final int INSERT = 0;
	public static final int UPDATE = 1;
	public static final int DELETE_BY_ID = 2;
	public static final int DELETE_BY_DESCRIPTION = 3;
	public static final int FIND_BY_ID = 4;
	public static final int FIND_BY_DESCRIPTION = 5;
	
	private String id = "";
	private String description = "";
	private String brand = "";
	private String model = "";
	private String method = "";
	
	private static final String url = "http://192.168.0.103:8080/Inventario/services/WebService";
	
    private int responseCode;
    private int methodId;
    private String message;
 
    private String response;
 
    public String getResponse() {
        return this.response;
    }
    
    public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
    public String getDescription() {
    	return this.browserToString(this.description);
    }
    
    public void setDescription(String description) {
    	this.description = this.stringToBrowser(description);
    }
    
    public String getBrand() {
		return this.browserToString(brand);
	}

	public void setBrand(String brand) {
		this.brand = this.stringToBrowser(brand);
	}

	public String getModel() {
		return this.browserToString(model);
	}

	public void setModel(String model) {
		this.model = this.stringToBrowser(model);
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(int method) {
		this.methodId = method;
		switch(methodId){
			case INSERT:
				this.method = "/insertGuitar?description=" + this.description + "&model=" + this.model +
				"&brand=" + this.brand;
				break;
			case UPDATE:
				this.method = "/updateGuitar?id=" + this.id + "&description=" + this.description + "&model="
				+ this.model + "&brand=" + this.brand;
				break;
			case DELETE_BY_ID:
				this.method = "/deleteGuitarById?id=" + this.id;
				break;
			case DELETE_BY_DESCRIPTION:
				this.method = "/deleteGuitarByDescription?description=" + this.description;
				break;
			case FIND_BY_ID:
				this.method = "/findGuitarById?id=" + this.id;
				break;
			case FIND_BY_DESCRIPTION:
				this.method = "/findGuitarByDescription?description=" + this.description;
				break;
		}
	}
 
    public String getErrorMessage() {
        return this.message;
    }
 
    public int getResponseCode() {
        return this.responseCode;
    }
    
    public void Execute() throws Exception{
    	HttpGet request = new HttpGet(url + this.method);
    	this.executeRequest(request, url);
    }
    	
    private void executeRequest(HttpUriRequest request, String url)
    {
    	HttpClient client = new DefaultHttpClient();

    	HttpResponse httpResponse;

    	try {
    		httpResponse = client.execute(request);
    		this.responseCode = httpResponse.getStatusLine().getStatusCode();
    		this.message = httpResponse.getStatusLine().getReasonPhrase();

    		HttpEntity entity = httpResponse.getEntity();

    		if (entity != null) {

    			InputStream instream = entity.getContent();
    			this.response = convertStreamToString(instream);
    			this.response = cleanString(this.response);

    			// Closing the input stream will trigger connection release
    			instream.close();
    		}

    	} catch (ClientProtocolException e)  {
    		client.getConnectionManager().shutdown();
    		e.printStackTrace();
    	} catch (IOException e) {
    		client.getConnectionManager().shutdown();
    		e.printStackTrace();
    	}
    }

    private static String convertStreamToString(InputStream is) {

    	BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    	StringBuilder sb = new StringBuilder();

    	String line = null;
    	try {
    		while ((line = reader.readLine()) != null) {
    			sb.append(line + "\n");
    		}
    	} catch (IOException e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			is.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	return sb.toString();
    }

    private String cleanString(String value){
    	String[] values = value.split("<ns:return>");
    	values = values[1].split("</ns:return>");
    	return values[0];
    }

    private String stringToBrowser(String value){
    	return value.replace(" ", "%20");
    }

    private String browserToString(String value){
    	return value.replace("%20", " ");
    }
}
